import Ext from "@/common/web_extension";
import { panelUrl, getPanelTab, getPlayTab } from '@/ext/common/tab'
import { delay, splitIntoTwo } from '@/common/utils'
import { activateTab } from '@/common/tab_utils'
import { resizeViewportOfTab } from '@/ext/common/resize_window'

export const panelNotifyAutoPause = () => {
    Ext.notifications.create({
        type: 'basic',
        iconUrl: './logo.png',
        title: 'Replay paused!',
        message: 'Auto paused by command',
    });
};

export const panelNotifyBreakpoint = () => {
    Ext.notifications.create({
        type: 'basic',
        iconUrl: './logo.png',
        title: 'Replay paused!',
        message: 'Auto paused by breakpoint',
    });
};

const getAllWindows = async () => {
    return new Promise((resolve) => {
        Ext.windows.getAll({}, (windows: any[]) => {
            resolve(windows)
        });
    })
}

// 截视口可见区域
export const captureVisibleTabAsync = async (windowId: number, options: any = { format: 'png' }) => {
    return await new Promise((resolve) => {
        Ext.tabs.captureVisibleTab(windowId, options, (dataUrl: string) => {
            resolve(dataUrl)
        })
    })
}

// 截全屏
export const captureFullScreenAsync = async (tabId: number) => {
    const tab: any = await getPlayTab()
    // 附加调试器到当前标签页
    await Ext.debugger.attach({ tabId: tab.id }, "1.3");
    // 发送Page.captureScreenshot命令，设置captureBeyondViewport为true
    const data: any = await Ext.debugger.sendCommand({ tabId: tab.id }, "Page.captureScreenshot", {
        format: "png",
        captureBeyondViewport: true,  // 关键参数，截图超出视口
        fromSurface: true
    });
    const dataUrl = `data:image/png;base64,${data.data}`;
    // 关闭调试器
    await Ext.debugger.detach({ tabId: tab.id });
    return dataUrl
}

// 除了panel，最小化其他窗口
export const panel_minimize_all_windows_but_panel = async () => {
    const wins: any = await getAllWindows()
    const panelTab: any = await getPanelTab()
    const list = wins.filter((win: any) => win.id !== panelTab.windowId);
    return Promise.all(list.map((win: any) => Ext.windows.update(win.id, { state: 'minimized' })))
        .then(() => delay(() => true, 500));
}

//  把播放页置顶
export const panel_bring_playing_window_to_foreground = async () => {
    try {
        const tab: any = await getPlayTab()
        await activateTab(tab.id, true)
    } catch (error) {

    }
}

// 最小化全部window
export const panel_minimize_all_windows = async () => {
    const wins: any = await getAllWindows()
    return await Promise.all(wins.map((win: any) => Ext.windows.update(win.id, { state: 'minimized' })))
        .then(() => delay(() => true, 500));
}

// 
export const panel_resize_play_tab = (args: any) => {
    return getPlayTab().then((tab: any) => resizeViewportOfTab(tab.id, args.viewportSize, args.screenAvailableRect));
}

// 关闭其他页签
export const panel_close_other_tabs = async () => {
    const tab: any = await getPlayTab();
    return Ext.tabs
        .query({ windowId: tab.windowId })
        .then((tabs: any) => tabs.filter((t: any) => t.id !== tab.id))
        .then((tabs: any) => Ext.tabs.remove(tabs.map((t: any) => t.id)));
}

// 关闭当前页签
export const panel_close_current_tab = async () => {

}

// 选择window
export const panel_select_window = async (args: { target: string, value: string }) => {
    const [type, locator] = splitIntoTwo('=', args.target);
    if (!locator) {
        throw new Error(`E207: invalid window locator, '${args.target}'`);
    }
}

export const panelStartPlaying = async (args: any) => {

}

export const panelStopPlaying = async () => { }

export const executeScript = async (tabId: number, target: string) => {
    const tab: any = await getPlayTab();
    const code = `Promise.resolve((function () { ${target} })());`
    return await new Promise((resolve, reject) => {
        Ext.scripting.executeScript({
            target: { tabId: tab.id, frameIds: [0] },
            func: (code: string) => {
                return window.eval(code);
            },
            args: [code],
            world: "MAIN"
        }, (res: any) => {
            if (Ext.runtime.lastError) {
                return reject(Ext.runtime.lastError)
            }
            resolve(res[0].result)
        })
    })
}

export const panelNotifyEcho = (text: string) => {
    Ext.notifications.create({
        type: 'basic',
        iconUrl: './logo.png',
        title: 'Echo',
        message: text,
    });
};


export const panelSetProxy = (args: any) => {
    const { proxy } = args;
    if (proxy) {
        Ext.proxy.set(proxy);
    } else {
        Ext.proxy.set(null);
    }
}